# -*- coding: utf-8 -*-
# @Time    : 2025/4/19 13:25
# @Author  : 我没有会员
# @FileName: BaiduWenku.py
# @Software: PyCharm
# @Blog    ：https://blog.csdn.net/csdnVIP071210

import requests
import os
from lxml import etree
from pptx import Presentation
from pptx.util import Inches


def create_file(file_path):
    if not os.path.exists(file_path):
        os.makedirs(file_path)

url = "https://wenku.baidu.com/view/714fc380de88d0d233d4b14e852458fb770b38e8.html?fr=income4-doc-search&_wkts_=1745566316056&wkQuery=%E8%BD%AF%E4%BB%B6%E7%BC%96%E7%A0%81%E9%A3%8E%E6%A0%BC%E6%B5%8B%E8%AF%95"

resp = requests.get(url)

text = resp.text


html = etree.HTML(text)
img_list = html.xpath("//div[@class='mod flow-ppt-mod']/div/div/img")

# 计数
count = 1

# 文件保存路径
file_path = "./wendang/"
create_file(file_path)
# 清空文件夹
for file in os.listdir(file_path):
    os.remove(os.path.join(file_path, file))

for i in img_list:
    try:
        img_url = i.xpath("./@src")[0]
    except:
        img_url = i.xpath("./@data-src")[0]

    # 命名排序前补足0

    file_name = f'{file_path}page_{str(count).zfill(3)}.jpg'
    print(file_name, img_url)
    resp = requests.get(img_url)
    with open(file_name, 'wb') as f:
        f.write(resp.content)

    count += 1

# 创建一个新的演示文稿
prs = Presentation()

# 图片列表
# 根据目录下文件生成文件列表
images = os.listdir(file_path)

# 获取幻灯片的尺寸
slide_width = prs.slide_width
slide_height = prs.slide_height

# 将 EMU 转换为厘米
slide_width_cm = slide_width / 914400 * 2.54
slide_height_cm = slide_height / 914400 * 2.54

for image in images:
    # 添加一个幻灯片
    slide_layout = prs.slide_layouts[6]  # 使用空白布局
    slide = prs.slides.add_slide(slide_layout)

    # 计算图片的尺寸
    img_path = os.path.join(file_path, image)
    from PIL import Image
    with Image.open(img_path) as img:
        img_width, img_height = img.size

    # 计算图片的宽高比
    aspect_ratio = img_width / img_height

    # 选择铺满幻灯片的宽度或高度
    if slide_width_cm / slide_height_cm > aspect_ratio:
        # 图片的高度铺满幻灯片
        height = slide_height
        width = int(height * aspect_ratio)
    else:
        # 图片的宽度铺满幻灯片
        width = slide_width
        height = int(width / aspect_ratio)

    # 插入图片并铺满幻灯片的一边
    left = (slide_width - width) // 2
    top = (slide_height - height) // 2
    pic = slide.shapes.add_picture(img_path, left, top, width, height)

# 保存演示文稿
prs.save('C:\\Users\\16515\\Desktop\\CCSFU\\2024-2025.第二学期\\1111\\' + 'output1111.pptx')

